<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Shop;
use App\Server\AliOSS;
use App\Server\Constants;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

class ShopController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Shop(), function (Grid $grid) {

            $grid->filter(function (Grid\Filter $filter) {
//                $filter->expand();
//                $filter->panel();
                $filter->like('name', '名称');
                $filter->equal('city', '区县')->select(Constants::$city);
                $filter->like('boos_phone', '电话');
            });

            $grid->showActions();
            $grid->disableRowSelector();
            $grid->disableViewButton();
            $grid->scrollbarX();
            $grid->model()->orderByDesc('id');

            $grid->column('id')->sortable();
            $grid->column('name');
            $grid->column('city')->display(function($code) {
                return Constants::$city[$code];
            });
            $grid->column('phone', '电话')->display(function($phone) {
                return $phone ?? '-';
            });
            $grid->column('map_latlng', '位置')->display(function ($latlong) {
                $key = env('.TENCENT_MAP_API_KEY');
                return "<a href='https://apis.map.qq.com/uri/v1/geocoder?coord={$latlong}&referer={$key}' target='_blank'>查看地图</a>";
            });
            $grid->column('status')->switch();
            $grid->column('img', '照片')->display(function($img) {
                return AliOSS::getBannerName($img);
            })->image(env('ALIYUN_DOMAIN'), 100);
        });
    }


    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Shop(), function (Form $form) {
            $form->display('id');
            $form->text('name')->required();
            $form->text('phone', ' 电话');
            $form->select('city')->options(Constants::$city)->required();
            $form->text('address')->required();
            $form->text('map_latlng', '地图坐标')->required()->help("坐标拾取: https://lbs.qq.com/getPoint");
            $form->map('map_lat', 'map_lng', '腾讯地图');
            $form->image('img', '照片')->required();
            $form->switch('status')->default(1);
            $form->saving(function (Form $form) {
                if ($form->img) {
                    $oss = new AliOSS();
                    $oss->createBanner($form->img, 9, 5);
                    if ($form->map_latlng) {
                        $map = explode(',', $form->map_latlng);
                        $form->map_lat = $map[0];
                        $form->map_lng = isset($map[1]) ? $map[1] : '';
                    }
                }
            });
        });
    }
}